package com.orange.hystrix.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.orange.cloud.domain.CommonResult;
import com.orange.cloud.domain.User;
import com.orange.hystrix.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/user")
public class UserHystrixController {

    @Autowired
    private UserService userService;

    @GetMapping("/testFallback/{id}")
    public CommonResult testFallback(@PathVariable Long id){
        return this.userService.getUser(id);
    }

    @GetMapping("testCommand/{id}")
    public CommonResult testCommand(@PathVariable Long id){
        return this.userService.getUserCommand(id);
    }

    @GetMapping("/testException/{id}")
    public CommonResult testException(@PathVariable Long id){
        return this.userService.getUserException(id);
    }

    @GetMapping("/testCache/{id}")
    public CommonResult testCache(@PathVariable Long id){
        this.userService.getUserCache(id);
        this.userService.getUserCache(id);
        this.userService.getUserCache(id);
        return CommonResult.ok("操作成功");
    }

    @GetMapping("/testRemoveCache/{id}")
    public CommonResult testRemoveCache(@PathVariable Long id){
        this.userService.getUserCache(id);
        this.userService.removeCache(id);
        this.userService.getUserCache(id);
        return CommonResult.ok("操作成功");
    }

    @GetMapping("/testCollapser")
    public CommonResult testCollapser() throws ExecutionException, InterruptedException {
        Future<User> future = this.userService.getUserFuture(1L);
        Future<User> future1 = this.userService.getUserFuture(2L);
        future.get();
        future1.get();
        // 再间隔200ms以后进行第三次服务调用
        ThreadUtil.safeSleep(200);
        Future<User> future2 = this.userService.getUserFuture(3L);
        future2.get();
        return CommonResult.ok("操作成功！");
    }
}
